package com.ruoyi.quartz.task;

import com.crm.custinfo.service.ICustInfoService;
import com.ruoyi.framework.datasource.DynamicDataSourceContextHolder;
import com.ruoyi.framework.datasource.DynamicRoutingDataSource;
import com.ruoyi.tenant.domain.MasterTenant;
import com.ruoyi.tenant.service.IMasterTenantService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 功能说明: 自动检测待分配任务列表数据并进行分配
 * 系统版本: v1.0
 * 开发人员: Mr.Wen
 * 开发时间: 2024/02/19
 */
@Slf4j
@Component("autoDistributeCustDatasTask")
public class AutoDistributeCustDatasTask {
    @Autowired
    private ICustInfoService iCustInfoService;
    @Autowired
    private DynamicRoutingDataSource dynamicRoutingDataSource;
    public void  autoDistributeCustDatas(){
        //实现切换数据源
        DynamicDataSourceContextHolder.setDataSourceKey("zk");
        MasterTenant masterTenant = new MasterTenant();
        masterTenant.setStatus("1");
        //获取所有启用的租户,并补全数据库链接信息
        List<MasterTenant> masterTenants = dynamicRoutingDataSource.getTenantListLoadDataSource(masterTenant);
        for (MasterTenant masterTenant1 : masterTenants) {
            if("zk".equals(masterTenant1.getTenant())){
                //跳过总库租户
                continue;
            }
            DynamicDataSourceContextHolder.setDataSourceKey(masterTenant1.getTenant());
            log.info("开始自动分配数据，当前线程数据库："+DynamicDataSourceContextHolder.getDataSourceKey());
            iCustInfoService.autoDistributeCustDatas();
        }
    }
}
